package com.apache.log.es.config;

import com.google.gson.GsonBuilder;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;

/**
 * @description: 获取JestClient客户端连接工厂类
 * @author: Hou Dayu
 * @date: Created in 2020/2/21
 */
public class EsClientFactory {

    public static JestClient buildEsClient(String jestHost, int maxTotal,int readTimOut,int connTimeOut){
        try {
            HttpClientConfig.Builder config = new HttpClientConfig.Builder(jestHost)
                    .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create()).readTimeout(readTimOut>0?readTimOut:20000)
                    .connTimeout(connTimeOut>0?connTimeOut:1500).multiThreaded(true);
            if (maxTotal > 0) {
                //一个route 默认不超过2个连接  路由是指连接到某个远程注解的个数。总连接数=route个数 * defaultMaxTotalConnectionPerRoute
                config.defaultMaxTotalConnectionPerRoute(maxTotal);
            }
            JestClientFactory factory = new JestClientFactory();
            factory.setHttpClientConfig(config.build());
            return factory.getObject();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
